let express=require('express');
let router = express.Router();
let url=require('url');



router.get('/', function(req, res, next) {
  var str=url.parse(req.url,true).query;
  console.log(str)
  var pool = global.POOL;
  var query = async () => {
    var connect = await pool.connect()
    try {
      if(str.q){
        str=str.q.split('');
        str=str.join('%');
        str=`%${str}%`
        console.log(str)
        const result=await connect.query(`SELECT title,module_name,id AS contentid FROM contents WHERE CONCAT(title,content) Like $1::text and posted=$2::boolean and deleted=$3::boolean`,[str,true,false])
        console.log(result.rows)
        let r=result.rows.map((item)=>{
          return {title:item.title,url:item.module_name+'/'+item.contentid}
        })
        console.log(r)
        res.send(r)
      }
      
    } finally {
      connect.release()
    }
  }

  query().catch(e => {
    res.send({question:'error'});
    console.error(e.message, e.stack)});
});
 
module.exports = router;
